<template>
  <div class="sporadic-demand-receive-container page-main">
    <query-page
      ref="sdemandPageRef"
      v-model:selectedKeys="selectedKeys"
      :form-component-config="formComponentConfig"
      :form-render-config="formRenderConfig"
      :form-render-keys="formRenderKeys"
      :table-component-config="tableComponentConfig"
      :table-render-config="tableRenderConfig"
      :table-render-keys="tableRenderKeys"
      :loading="isLoading"
      :data="renderData"
      :total="total"
      :has-line="false"
      title="零星需求接收与确认"
      row-selection-type="checkbox"
      @selection-change="selectionChange"
      @query-data="getData"
    >
      <template #top-container>
        <p-tabs
          v-model:value="activeTab"
          :is-show-num="false"
          :tab-list="materialType"
          style="margin: 0 0 8px"
        />
      </template>
      <template #header-ext-container>
        <a-radio-group v-model="activeRadio" type="button" class="radio-ara">
          <a-radio value="1">新增需求</a-radio>
          <a-radio value="2">变更需求</a-radio>
          <a-radio value="3">已确认需求</a-radio>
        </a-radio-group>
      </template>
      <template #container-side>
        <batchBtn
          :btn-list="btnList"
          :other-params="{
            activeTab,
            activeRadio,
            functionType: 2,
            selection: selection,
          }"
          @result="clickResult"
        />
      </template>
      <template #operate="{ record, rowIndex }">
        <batchBtn
          :btn-list="rowBtnList"
          :other-params="{
            record,
            rowIndex,
            activeTab,
            activeRadio,
            functionType: 2,
          }"
          type="2"
          @result="rowClickResult"
        />
      </template>
    </query-page>
    <!-- 是否采购 -->
    <purchaseDialog
      v-if="purchaseVisible"
      :selection="selection"
      :tab-param="{
        classType: activeTab,
        queryType: activeRadio,
        functionType: 2,
      }"
      @close-drawer="closeDrawer"
      @success="success"
    />
    <!-- 手动关闭 -->
    <closeDialog
      v-if="closeVisible"
      :selection="selection"
      :tab-param="{
        classType: activeTab,
        queryType: activeRadio,
        functionType: 2,
      }"
      @close-drawer="closeDrawer"
      @success="success"
    />
    <!-- 导入 -->
    <importDialog
      v-if="importVisible"
      :type="allBtnType"
      :tab-param="{
        classType: activeTab,
        queryType: activeRadio,
        functionType: 2,
      }"
      @close-drawer="imCloseDrawer"
      @success="success"
    />
    <!-- 详情 -->
    <detailDialog
      v-if="detailVisible"
      :type="activeTab + activeRadio"
      :row-data="oprationRowData"
      @close-drawer="closeDrawer"
    />
    <loadDialog v-if="loadVisible" :total="total" />
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted, watch, nextTick } from 'vue';
  import queryPage from '@/common/components/query-page/index.vue';
  import lodash from 'lodash';
  import { materialType } from '@/config/const';
  import { hasDataAndBack, dateFormatter } from '@/common/utils/index';
  import {
    formRenderConfig,
    formComponentConfig,
  } from '@/views/purchase-demand/components/formComp/baseFormConfig';
  import {
    tableRenderConfig,
    tableComponentConfig,
  } from '@/views/purchase-demand/components/tableComp/baseTableConfig';
  import {
    getDemandPage,
    allDemandConfirmList,
  } from '@/api/purchase-demand/supportDemandReceive';
  import { info } from '@/common/utils/modal-promise';
  import { Message } from '@arco-design/web-vue';
  import { baseRenderKeys } from './baseData';
  import { getBtnList } from './baseBtn';
  import { getRowBtnList } from './rowBaseBtn';
  import batchBtn from '../components/batchBtn.vue';
  import PTabs from '../components/p-tabs.vue';
  import purchaseDialog from '../components/purchaseDialog.vue';
  import closeDialog from '../components/closeDialog.vue';
  import importDialog from '../components/importDialog.vue';
  import detailDialog from './detail.vue';
  import loadDialog from '../components/loadDialog.vue';

  const selectedKeys = ref([]);
  const selection = ref<any[]>([]);
  const activeTab = ref('');
  const activeRadio = ref('');
  const isLoading = ref(true);
  const renderData = ref<any[]>([]);
  const closeVisible = ref(false);
  const importVisible = ref(false);
  const purchaseVisible = ref(false);
  const detailVisible = ref(false);
  const loadVisible = ref(false);
  const allBtnType = ref('');
  const total = ref(0);
  const sdemandPageRef = ref();
  const oprationRowData = ref<any>();
  // 渲染检索项
  const formRenderKeys = ref<any[]>([]);
  // 当前表格要渲染哪些值
  const tableRenderKeys = ref<any[]>([]);
  const btnList = ref<any[]>([]);
  const rowBtnList = ref<any[]>([]);
  const getData = async (queryInfo: object) => {
    renderData.value = [];
    isLoading.value = true;
    const param: any = { ...queryInfo };
    // 需求时间
    if (param.requireDateStart || param.requireDateEnd) {
      param.requireDate = dateFormatter(
        param.requireDateStart,
        param.requireDateEnd
      );
    }
    // 需求下达时间
    if (param.requireDispatchDateStart || param.requireDispatchDateEnd) {
      param.requireDispatchDate = dateFormatter(
        param.requireDispatchDateStart,
        param.requireDispatchDateEnd
      );
    }
    param.functionType = 2;
    param.classType = activeTab.value ? Number(activeTab.value) : 2;
    param.queryType = activeRadio.value ? Number(activeRadio.value) : 1;
    const res: any = await getDemandPage(param);
    if (res.code === 200) {
      total.value = res.data.total;
      renderData.value = [...res.data.list];
      refreshNumData(renderData.value, total.value);
    }
    isLoading.value = false;
  };
  const refreshNumData = (list: any[], tNum: any) => {
    if (hasDataAndBack(list, tNum, sdemandPageRef.value?.getStatus().pageNo)) {
      sdemandPageRef.value?.setCurrent(
        sdemandPageRef.value.getStatus().pageNo - 1
      );
      getData(sdemandPageRef.value.getStatus());
    }
  };
  const selectionChange = (val: string[]) => {
    console.log('selectedKeys', val);
    selection.value = renderData.value.filter((item: any) => {
      return selectedKeys.value.includes(item.id);
    });
  };
  /**
   * 按钮区域点击事件
   * type: 1:批量备注; 2:导入; 3:手动关闭;4:指定是否采购; 5:导入需要手工关闭的需求;9:全部确认
   */
  const clickResult = (type: string) => {
    allBtnType.value = type;
    oprationRowData.value = null;
    switch (type) {
      case '2':
      case '5':
        importVisible.value = true;
        break;
      case '3':
        closeVisible.value = true;
        break;
      case '4':
        purchaseVisible.value = true;
        break;
      case '9':
        allConfirmation();
        break;
      default:
        initData();
        refreshData();
        break;
    }
    console.log('type', type);
  };
  // 全部确认
  const allConfirmation = async () => {
    await info({
      title: `您确定要确认当前所有${total.value}条的需求？`,
      content: '',
      hideCancel: false,
    });
    const par = {
      functionType: 2,
      classType: activeTab.value,
      queryType: activeRadio.value,
    };
    console.log('par', par);
    loadVisible.value = true;
    try {
      const res: any = await allDemandConfirmList(par);
      if (res.code === 200) {
        Message.success('确认成功');
        refreshData();
      }
    } catch (error) {
      Message.success('确认失败');
    } finally {
      loadVisible.value = false;
    }
  };
  // 列表操作列点击事件 1: 备注
  const rowClickResult = (type: string, rowParams: any) => {
    console.log('111111', type, rowParams);
    oprationRowData.value = rowParams.record;
    switch (type) {
      case '2':
        detailVisible.value = true;
        break;
      default:
        initData();
        getData(sdemandPageRef.value.getStatus());
        break;
    }
  };
  const tabType = ref<any>({
    '1': 'standardPart',
    '2': 'finishedProduct',
    '3': 'rawMaterial',
    '4': 'zeroCom',
    '5': 'forgingAndCasting',
  });
  const tableRenderType = ref<any>({
    '1': 'newTableRenderKeys',
    '2': 'cmTableRenderKeys',
    '3': 'rTableRenderKeys',
  });
  // 初期话
  const initData = () => {
    // 获取列表的renderKey(列表渲染项)
    const key = `${activeTab.value}${activeRadio.value}`;
    const tableRender = lodash.cloneDeep(
      baseRenderKeys[tabType.value[activeTab.value]][
        tableRenderType.value[activeRadio.value]
      ]
    );
    if (['13', '23', '33', '43', '53'].includes(key)) {
      tableRenderKeys.value = [...tableRender];
    } else {
      tableRenderKeys.value = [...tableRender, 'operate'];
    }
    // 获取筛选form的renderKey(表单渲染项)
    formRenderKeys.value = lodash.cloneDeep(
      baseRenderKeys[tabType.value[activeTab.value]].formRenderKeys
    );
    // 获取表格上方按钮
    btnList.value = getBtnList(activeTab.value, activeRadio.value);
    // btnList.value = btnList.value.filter((item) => item.name !== '重新校验');
    // 获取列表操作列按钮
    rowBtnList.value = getRowBtnList(activeTab.value, activeRadio.value);
    rowBtnList.value = rowBtnList.value.filter((item) => item.name !== '详情');
    console.log('rowBtnList.value', rowBtnList.value, key);
  };
  const refreshData = () => {
    sdemandPageRef.value.setCurrent(1);
    selection.value = [];
    selectedKeys.value = [];
    getData(sdemandPageRef.value.getStatus());
  };
  watch(activeTab, () => {
    initData();
    nextTick(() => {
      sdemandPageRef.value?.formReset();
      refreshData();
    });
  });
  watch(activeRadio, () => {
    initData();
    refreshData();
  });
  onMounted(() => {
    activeTab.value = '2';
    activeRadio.value = '1';
    initData();
  });
  const imCloseDrawer = () => {
    getData(sdemandPageRef.value.getStatus());
    closeDrawer();
  };
  // 关闭弹窗
  const closeDrawer = () => {
    closeVisible.value = false;
    purchaseVisible.value = false;
    importVisible.value = false;
    detailVisible.value = false;
  };
  // 关闭弹窗
  const success = () => {
    closeVisible.value = false;
    purchaseVisible.value = false;
    importVisible.value = false;
    initData();
    getData(sdemandPageRef.value.getStatus());
  };
</script>

<style lang="less" scoped>
  .sporadic-demand-receive-container {
    display: flex;
    flex-direction: column;
    height: calc(100vh - 125px);
    overflow: hidden;

    :deep(.page-title) {
      padding-bottom: 6px !important;
    }

    .radio-ara {
      width: 100%;
      margin-top: 16px;
      background-color: #e4e7ed !important;

      :deep(.arco-radio-checked) {
        color: #1e2228 !important;
      }

      :deep(.arco-radio-button) {
        flex: 1;
        text-align: center;
      }
    }
  }
</style>
